package com.it.handler;

import com.it.exception.BaseException;
import com.it.pojo.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     *
     * @param baseException
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException baseException) {
        log.info("全局异常处理：{}", baseException.getMessage());
        return Result.error(baseException.getMessage());
    }

    /**
     * 捕获SQL异常
     *
     * @param ex
     * @return
     */
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String usename = split[2];
            return Result.error(usename + "已存在");
        } else {
            return Result.error("未知错误");
        }

    }


}
